#define _CRT_SECURE_NO_WARNINGS 1

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    TreeNode* pruneTree(TreeNode* root)
    {
        //if(root==nullptr)return nullptr;
        if (dfs(root) == 1)return root;
        else return nullptr;
    }

    int dfs(TreeNode* root)
    {
        //cout<<11111<<endl;
        if (root->left == nullptr && root->right == nullptr)return root->val;
        bool left;
        if (root->left != nullptr) left = dfs(root->left);
        bool  right;
        if (root->right != nullptr) right = dfs(root->right);

        if (left == 0)root->left = nullptr;
        if (right == 0)root->right = nullptr;

        if (root->left == nullptr && root->right == nullptr)return root->val;
        else return 1;
    }
};